// electron-main/index.ts
import { app, BrowserWindow, ipcMain } from "electron";
import path from "path";
import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer';

let bluetoothPinCallback: any
let selectBluetoothCallback: any

const createWindow = () => {
  const win = new BrowserWindow({
    autoHideMenuBar: true,
    width: 1000,
    height: 800,
    frame: false,
    resizable: false,
    // transparent:true,
    webPreferences: {
      devTools: true,
      contextIsolation: true, // 是否开启隔离上下文
      nodeIntegration: true, // 渲染进程使用Node API
      preload: path.join(__dirname, "../electron-preload/index.js"), // 需要引用js文件
    },

  });
  win.webContents.openDevTools();

  win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => {
    event.preventDefault()
    selectBluetoothCallback = callback
    console.log(deviceList)
    const result = deviceList.find((device) => {
      return device.deviceName === 'test'
    })
    if (result) {
      callback(result.deviceId)
    } else {
      // The device wasn't found so we need to either wait longer (eg until the
      // device is turned on) or until the user cancels the request
    }
  })

  ipcMain.on('cancel-bluetooth-request', (event) => {
    selectBluetoothCallback('')
  })


  // Listen for a message from the renderer to get the response for the Bluetooth pairing.
  ipcMain.on('bluetooth-pairing-response', (event, response) => {
    bluetoothPinCallback(response)
  })

  win.webContents.session.setBluetoothPairingHandler((details, callback) => {

    bluetoothPinCallback = callback
    // Send a message to the renderer to prompt the user to confirm the pairing.
    win.webContents.send('bluetooth-pairing-request', details)
  })

  // 如果打包了，渲染index.html
  if (app.isPackaged) {
    win.loadFile(path.join(__dirname, "../dist/index.html"));
  } else {
    let url: string = process.env.VITE_DEV_SERVER_URL ? process.env.VITE_DEV_SERVER_URL : ""; // 本地启动的vue项目路径
    win.loadURL(url);
  }
  //小化
  ipcMain.on('hide-window', (e: Event, data: string) => {
    win.minimize();
    console.log(data);
  });
  // 监听渲染进程方法
  ipcMain.on("close-window", (e: Event, data: string) => {
    console.log(data);
    if (process.platform !== "darwin") {
      app.quit();
    } else {
      e.preventDefault();
      win.hide();
    }
  });
};



app.whenReady().then(() => {
  createWindow(); // 创建窗口
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

// app.whenReady().then(() => {
//   installExtension(VUEJS3_DEVTOOLS)
//     .then((name) => console.log(`Added Extension:  ${name}`))
//     .catch((err) => console.log('An error occurred: ', err));
// });
// 关闭窗口
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on('before-quit', () => {

})


